// web/main.dart
import 'dart:html';
import 'dart:convert'; // 用于 JSON 编码解码

// 代表一个待办事项
class Task {
  String text;
  bool completed;

  Task(this.text, {this.completed = false});

  // --- JSON 序列化/反序列化 ---
  Map<String, dynamic> toJson() => {'text': text, 'completed': completed};

  factory Task.fromJson(Map<String, dynamic> json) {
    final text = json['text'] as String;
    final completed = json['completed'] as bool? ?? false;
    return Task(text, completed: completed);
  }
}

void main() {
  // --- 获取 DOM 元素 ---
  final InputElement? input = querySelector('#new-task-input') as InputElement?;
  final ButtonElement? button =
      querySelector('#add-task-btn') as ButtonElement?;
  final UListElement? taskList = querySelector('#task-list') as UListElement?;

  if (input == null || button == null || taskList == null) {
    print('错误：无法找到必要的 HTML 元素！请检查 ID 是否正确。');
    return;
  }

  // --- 状态管理 ---
  List<Task> tasks = [];

  // --- 辅助函数声明 (调整顺序以修复引用错误) ---

  // *** saveTasks 定义移到 renderTasks 和 loadTasks 之前 ***
  void saveTasks() {
    final String encodedTasks =
        jsonEncode(tasks.map((t) => t.toJson()).toList());
    window.localStorage['tasks'] = encodedTasks;
  }

  // *** renderTasks 定义移到 loadTasks 之前，但在 saveTasks 之后 ***
  void renderTasks() {
    taskList.children.clear();

    for (final task in tasks) {
      final item = LIElement()
        ..className = 'task-item ${task.completed ? "completed" : ""}';

      // 声明 checkbox 变量
      final CheckboxInputElement checkbox = CheckboxInputElement()
        ..checked = task.completed
        // *** 修改点：在 onChange 回调中使用 event.target ***
        ..onChange.listen((Event event) {
          // 添加 Event 参数
          // 从事件目标获取当前的 checkbox 元素
          final currentCheckbox = event.target as CheckboxInputElement?;
          if (currentCheckbox != null) {
            // 更新任务状态
            task.completed = currentCheckbox.checked ?? false;
            saveTasks(); // 保存更改
            renderTasks(); // 重新渲染以更新样式
          }
        });

      final label = SpanElement()
        ..text = task.text
        ..className = 'task-text';

      final deleteBtn = ButtonElement()
        ..text = '删除'
        ..className = 'delete-btn'
        ..onClick.listen((_) {
          final currentIndex = tasks.indexOf(task);
          if (currentIndex != -1) {
            tasks.removeAt(currentIndex);
            saveTasks(); // 保存更改
            renderTasks(); // 重新渲染列表
          }
        });

      item.append(checkbox);
      item.append(label);
      item.append(deleteBtn);
      taskList.append(item);
    }
  }

  // 从 localStorage 加载任务列表
  void loadTasks() {
    final String? storedTasks = window.localStorage['tasks'];
    if (storedTasks != null) {
      try {
        final decodedList = jsonDecode(storedTasks) as List;
        tasks = decodedList
            .map((taskJson) => Task.fromJson(taskJson as Map<String, dynamic>))
            .toList();
      } catch (e) {
        print('从 localStorage 加载任务失败: $e');
        tasks = [];
        window.localStorage.remove('tasks');
      }
    } else {
      tasks = [];
    }
    renderTasks(); // 加载后重新渲染界面
  }

  // --- 事件处理 ---
  void addTask() {
    final text = input.value?.trim();
    if (text != null && text.isNotEmpty) {
      tasks.add(Task(text));
      input.value = '';
      saveTasks(); // saveTasks 已定义
      renderTasks(); // renderTasks 已定义
    }
    input.focus();
  }

  button.onClick.listen((_) => addTask());

  input.onKeyPress.listen((KeyboardEvent e) {
    if (e.key == "Enter") {
      addTask();
    }
  });

  // --- 初始化 ---
  loadTasks(); // 页面加载时，首先加载存储的任务
}
